/**
 * service: project
 *
 * @author    Dmitry Ustimov
 * @date      March 2012
 *
 */
package com.gr

class ProjectService {
	
	static transactional = true

	def DistributorService

	def getlist(params) {
		println(params)
		def divTo = Division.get(params.get("id"))
		return Project.findAllByDivisionToLike(divTo).collect{[
			text : it.title, 
			id   : ("Project_" + it.id)
		]}
	}
	
	def getlistAll() {
		return Project.list().collect{[
			text : it.title, 
			id   : it.title
		]}
	}
	
	def getElement(params) {
		println(params)
		def el = Project.get(params.get("id"))
		return [
			'success'  :'true', 
			id         : el.id, 
			title      : el.title, 
			email      : el.email, 
			startDate  : el.startDate, 
			divisionTo : el.divisionTo.title
		]
	}
	
	def addElement(params) {
		println(params)
		def divTo = Division.get(params.get("divisionTo"))
		if (divTo) {
			def newProj = new Project()
			newProj.title = params.get('title')
			newProj.email = params.get('email')
			newProj.startDate = new Date()
			newProj.divisionTo = divTo
			if (newProj.save()) {			
				return ['success':'true']
			}
			else {
				return ['success':'false']
			}
		}
		else {
			return ['success':'false']
		}
	}
	
	def editElement(params) {
		println(params)
		def divTo = Division.get(params.get("divisionTo"))
		if (divTo) {
			def newProj = Project.get(params.get('id'))
			newProj.title = params.get('title')
			newProj.email = params.get('email')
			newProj.startDate = new Date()
			if (params.get('startDate'))
				newProj.startDate = new Date(params.get('startDate'))
			else
				newProj.startDate = null
			newProj.divisionTo = divTo
			if (newProj.save()) {
				return ['success':'true']
			}
			else {
				return ['success':'false']
			}
		}
		else {
			return ['success':'false']
		}
	}
	
	def deleteElement(params) {
		println(params)
		
		def foundProj = Project.get(params.get("id"))
		def flist = Person.findAllByProjectToLike(foundProj)

		Iterator itr = flist.iterator()
		while(itr.hasNext()){
			def el = itr.next()
			itr.remove()
			el.delete()
		}

		foundProj.delete()
		
		return ['success':'true']
	}
}
